#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
Date   : 2019-12-07
"""
import uuid
import coreapi
import coreschema
from .base import ViewSecurityBase
from mmonitor.common.code_verify import captcha_verify
from mmonitor.utils.send_mail import send_mail
from mmonitor.models.cache import CacheInteractor
from mmonitor.models.mysql_db import UserModel


class ForgetPasswordView(ViewSecurityBase):
    get_fields = (
        coreapi.Field(
            name='url_id',
            location='query',
            description=u'web url_id',
            required=True,
            type="String",
            schema=coreschema.String()
        ),
    )
    cache = CacheInteractor()

    def get(self, request):

        return self.ok_response()

    def post(self, request):
        email = request.bget_string("email")
        verify = request.bget_dict("verify")

        if captcha_verify(verify) != 0:
            return self.error_response("验证码错误，请重新刷新页面")
        if not UserModel.get_or_none(UserModel.email == email):
            return self.error_response("请确认邮箱是否正确！")
        uid = str(uuid.uuid4()).replace("-", "_")

        self.cache.set(uid, email, life_cycle=5*60*1000)
        content = "尊敬的用户，您好: <br><br>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp请点击以下链接重设密码。http://www.jiankong.art/forget_password.html?token={} 如果链接无法点击，请将它复制到你的浏览器（如谷歌）地址栏中进入访问。有效期10分钟<br><br>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp有问题可以联系QQ 1033313711".format(uid)
        send_mail(email, subject="密码重置", body=content)
        return self.ok_response()

    def put(self, request):
        token = request.bget_string("token")
        email = request.bget_string("email")
        verify = request.bget_dict("verify")
        password = request.bget_string("password")
        mail = self.cache.get(token)
        if not mail or mail != email:
            return self.error_response("token已经失效了，请到忘记密码页面重新发送邮件进行尝试")

        if captcha_verify(verify) != 0:
            return self.error_response("验证码错误，请重新刷新页面")
        if not UserModel.get_or_none(UserModel.email == email):
            return self.error_response("请确认邮箱是否正确！")
        UserModel.update(**{"password": password}).where(UserModel.email == email).execute()

        return self.ok_response()

    def delete(self, request):

        return self.ok_response()
